package sg.edu.nus.iss.team2s.jass.dao;

/**
 * Default DAO implementation for JobAdvertResponse
 * @author Zheng Xiaofeng
 * @version 1.0
 */

import java.util.List;
import java.util.Iterator;
import sg.edu.nus.iss.team2s.jass.dto.JobAdvertResponse;

public class JobAdvertResponseDAO extends AbstractPropertiesDAO {
	public static final String FILENAME = "JobAdvertResponse";
	
	@Override
	public void add(Object obj) throws DAOException {
		JobAdvertResponse response = (JobAdvertResponse)obj;
		String jobAdvertId = response.getJobAdvertId();
		String jobSeekerId = response.getJobSeekerId();
		if(jobAdvertId == null || jobAdvertId.equals("")){
			throw new DAOException("The advert ID should not be empty!");
		}

		if(jobSeekerId == null || jobSeekerId.equals("")){
			throw new DAOException("The job seeker ID should not be empty!");
		}
		//validate the duplicate response
		List<Object> responseList = list();
		Iterator<Object> iterator = responseList.iterator();
		while(iterator.hasNext()){
			JobAdvertResponse responseRec = (JobAdvertResponse)iterator.next();
			if(responseRec.getJobAdvertId().equalsIgnoreCase(jobAdvertId) && responseRec.getJobSeekerId().equalsIgnoreCase(jobSeekerId)){
				throw new DAOException("Duplicated Job Advert Response!");
			}
		}
		
		responseList.add(response);
		update(responseList);
	}

	@Override
	public Object get(String key) throws DAOException {
		List<Object> responseList = list();
		Iterator<Object> iterator = responseList.iterator();
		while(iterator.hasNext()){
			JobAdvertResponse responseRec = (JobAdvertResponse)iterator.next();
			String jobAdvertId = responseRec.getJobAdvertId();
			String jobSeekerId = responseRec.getJobSeekerId();
			String recordKey = jobAdvertId + "|" + jobSeekerId;
			if(recordKey.equalsIgnoreCase(key)){
				return responseRec;
			}
		}
		return null;
	}

	@Override
	public List<Object> list() throws DAOException {
		List<Object> list = retrieve(FILENAME);
		return list;
	}

	@Override
	public void update(List<Object> list) throws DAOException {
		flush(list, FILENAME);
	}

}
